/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ggsoft.webapp.action;

import com.ggsoft.timetracker.service.TimeTrackerService;
import java.io.Serializable;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.appfuse.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 *
 * @author giovanella
 * @date May 17, 2014
 */
public class TimeTrackerBean extends BasePage implements Serializable {
    
    private TimeTrackerService timeTrackerService;
    private String reason;
    
    public TimeTrackerBean() {
    }
    
    @Autowired
    public void setTimeTrackerService(@Qualifier("timeTrackerService") TimeTrackerService timeTrackerService) {
        this.timeTrackerService = timeTrackerService;
    }
    
    public String edit() {
        HttpServletRequest request = getRequest();
        Date date = new Date();
        System.out.println("User " + request.getRemoteUser());        
        User requestUser = userManager.getUserByUsername(request.getRemoteUser());
        
        if (requestUser != null) {
            System.out.println("Editing user " + requestUser.getFirstName() + " Status: " + requestUser.getStatus());
            String station = getCurrentIP();
            if (timeTrackerService.validateIp(station, requestUser.getAllowedIps())) {          
                System.out.println("Ip validated " + station  + "; Ips: " + requestUser.getAllowedIps());
                if (requestUser.getStatus() != null && requestUser.getStatus().equals("IN") && reason != null) {
                    timeTrackerService.punchTimeCard(requestUser, requestUser.getStatus(), reason, station);
                } else if (requestUser.getStatus() != null && requestUser.getStatus().equals("OUT")) {
                    timeTrackerService.punchTimeCard(requestUser, requestUser.getStatus(), null, station);
                } else {
                    addMessage("timecard.reason.required");
                    return "fail";
                }                
            } else {
                addError("timecardForm.invalidIp");
                return "fail";
            }
        }
        addMessage("timecard.success");
        return "success";
    }
    
    public String getReason() {
        return reason;
    }
    
    public void setReason(String reason) {
        this.reason = reason;
    }            
}
